import React, { useEffect, useState } from "react";
import { Row, Col, Input, Collapse } from 'antd';
import ReactMarkdown from 'react-markdown';
import remarkBreaks from 'remark-breaks';
import styles from '../Index.less';
import config from '../../../config/config';
import * as commonUtil from '../../../utils/commonUtil';

const { Panel } = Collapse;

const TextChatPage = (props) => {

    console.log("ChatMessagePage props => ", props);

    const [ textChatMessages, setTextChatMessages ] = useState([]);
    const [ showBlodSuffix, setShowBlodSuffix ] = useState(false);

    useEffect(() => {
        let textChatList = [
            { id: commonUtil.generateUUID(), type: "user", think: "", answer: "111111111111111111111111111111111111111111111111111" },
            { id: commonUtil.generateUUID(), type: "ai", think: "", answer: "2222222222222222222222222222222222222222222222222" },
            { id: commonUtil.generateUUID(), type: "user", think: "", answer: "3333333333333333333333333333333333333333333333" },
            { id: commonUtil.generateUUID(), type: "ai", think: "", answer: "444444444444444444444444444444444444444444444444444" },
        ];
        setTextChatMessages(textChatList);
    }, []);

    const onSendChatText = () => {
        let domInput = document.getElementById("textChatInput");
        if (!domInput.value) {
            return;
        }

        textChatMessages.push({ id: commonUtil.generateUUID(), type: "user", think: "", answer: domInput.value });
        setTextChatMessages(textChatMessages);

        const msgId = commonUtil.generateUUID();
        textChatMessages.push({ id: msgId, type: "ai", think: "", answer: "" });
        setTextChatMessages(textChatMessages);

        const prompt = "你是一个聊天高手，请回答以下问题：" + domInput.value;
        postChatMessage(msgId, prompt);
    }

    const postChatMessage = (msgId, prompt) => {
        const eventSource = new EventSource(config.api.modal.postChatMessage + "?prompt=" + prompt);
        console.log("postChatMessage eventSource => ", eventSource);

        let endThinkFlag = false;
        eventSource.onmessage  = function(e) {
            let data = JSON.parse(e.data).trim();
            console.log("postChatMessage onmessage data => ", data);
            if ("Responsing" == data?.error) {
                return;
            }

            if (data.indexOf("<think>") > -1) {
                data = data.replaceAll("<think>", "")
            }
            if (data.indexOf("</think>") > -1) {
                data = data.replaceAll("</think>", "")
                endThinkFlag = true;
            }

            let newTextObj = textChatMessages.find(item => msgId == item.id);
            if (!endThinkFlag) {
                newTextObj.think = newTextObj.think + data;
            } else {
                newTextObj.answer = newTextObj.answer + data;
            }
            setTextChatMessages([ ...textChatMessages ]);
        };

        eventSource.addEventListener('connect',  (e) => {
            console.log('Connected to server');
        });

        eventSource.addEventListener('complete',  (e) => {
            console.log('Streaming completed');
            eventSource.close();
        });
    }

    const createChatInputFixIcon = (fixType) => {
        if ("prefix" == fixType) {
            return (<i className="ri-user-3-line" style={{ fontSize: 20 }} />);
        }

        return (
            <span className={styles.text_chat_input_suffix} onMouseOver={() => setShowBlodSuffix(true)} onMouseOut={() => setShowBlodSuffix(false)}>
                <i className={showBlodSuffix ? "ri-chat-smile-2-fill" : "ri-chat-smile-2-line"} style={{ fontSize: 20, cursor: "pointer" }} onClick={() => onSendChatText()} />
            </span>
        );
    }

    return (
        <div style={{ width: "100%", padding: 20, display: "flex", flexDirection: "row" }}>
            <div style={{ flex: 5, margin: "0px 20px 0px 0px", background: "#9e9e9e12", display: "flex", flexDirection: "column" }}>
                <div style={{ flex: 5, lineHeight: 2.2, overflow: "auto", padding: "0px 0px 15px 0px" }}>
                    {
                        textChatMessages.map(item =>
                            <div style={{ padding: "15px 15px 0px 15px", textAlign: item.type == "user" ? "right" : "left", display: "flex", flexDirection: "row" }}>
                                <span style={{ flex: item.type == "user" ? 1 : 0 }}>
                                    <i className={"ri-robot-3-line"} style={{ display: item.type == "ai" ? "inline-block" : "none", fontSize: 20, padding: "0px 15px 0px 0px" }} />
                                </span>
                                <span style={{ display: "flex", flexDirection: "column" }}>
                                    <Collapse bordered={false} style={{ background: "#ffffff", display: item.think ? "block" : "none" }}>
                                        <Panel header={"思考过程"} key={"think"}>
                                            <ReactMarkdown remarkPlugins={[remarkBreaks]}>{item.think}</ReactMarkdown>
                                        </Panel>
                                    </Collapse>
                                    <span className={styles.text_chat_message_item}>
                                        <ReactMarkdown remarkPlugins={[remarkBreaks]}>{item.answer}</ReactMarkdown>
                                    </span>
                                </span>
                                <span style={{ flex: item.type == "user" ? 0 : 1 }}>
                                    <i className={"ri-user-3-line"} style={{ display: item.type == "user" ? "inline-block" : "none", fontSize: 20, padding: "0px 0px 0px 15px" }} />
                                </span>
                            </div>
                        )
                    }
                </div>
                <Input allowClear
                       id={"textChatInput"}
                       placeholder="请输入问题 。。。"
                       addonBefore={createChatInputFixIcon("prefix")}
                       addonAfter={createChatInputFixIcon("suffix")}
                />
            </div>
            <div style={{ flex: 2, borderLeft: "1px solid #9e9e9e59", lineHeight: 4 }}>
                <Row>
                    <Col span={6} style={{ textAlign: "right" }}>会话名称：</Col>
                    <Col span={18}><Input /></Col>
                </Row>
                <Row>
                    <Col span={6} style={{ textAlign: "right" }}>模型名称：</Col>
                    <Col span={18}><Input /></Col>
                </Row>
                <Row>
                    <Col span={6} style={{ textAlign: "right" }}>BaseUrl：</Col>
                    <Col span={18}><Input /></Col>
                </Row>
                <Row>
                    <Col span={6} style={{ textAlign: "right" }}>ApiKey：</Col>
                    <Col span={18}><Input /></Col>
                </Row>
                <Row>
                    <Col span={6} style={{ textAlign: "right" }}>系统消息：</Col>
                    <Col span={18}><Input /></Col>
                </Row>
                <Row>
                    <Col span={6} style={{ textAlign: "right" }}>TopK：</Col>
                    <Col span={18}><Input /></Col>
                </Row>
                <Row>
                    <Col span={6} style={{ textAlign: "right" }}>温度：</Col>
                    <Col span={18}><Input /></Col>
                </Row>
            </div>
        </div>
    );
}

export default TextChatPage;
